import type { IRequestData } from '@/types/request'
import axios, { HttpStatusCode } from 'axios'
import { ElMessage } from 'element-plus'

const $axios = axios.create({
  baseURL: import.meta.env.VITE_SERVER,
  timeout: 1000 * 60 * 60
})

$axios.interceptors.request.use(config => {
  const token = localStorage?.getItem('token')

  if (token) config.headers.Authorization = `Bearer ${token}`

  return config.data
})

$axios.interceptors.response.use(
  response => {
    const { code } = response.data

    let message: string = ''

    if (code === HttpStatusCode.Unauthorized) {
      message = '没有权限'
    }

    if (code === HttpStatusCode.Created) {
      message = '请求失败'
    }

    if (message) ElMessage.error(message)

    return response.data
  },
  error => {
    ElMessage.error(error)

    return Promise.reject(error)
  }
)

export const request = ({
  url = '',
  headers = { 'Content-Type': 'application/json' },
  method = 'GET',
  data = {},
  params = {}
}: IRequestData) => $axios({ url, method, data, params, headers })
